package com.cow.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.StringTokenizer;

import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;

import sun.misc.BASE64Decoder;

public class FileUtil {

	private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
	private static String accessKeyId = "LTAIvMxoeakjEj89";
	private static String accessKeySecret = "Ej5YNMtdy2jUHWDCPpVYbX6qaklX4j";
	private static String bucketName = "yunkaihuang";
	static OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

	public FileUtil() {

	}

	// base64字符串转化成图片
	public static File GenerateImage(String imgStr, String filePath) { // 对字节数组字符串进行Base64解码并生成图片
		BASE64Decoder decoder = new BASE64Decoder();
		String fileNameBefore = System.currentTimeMillis() + "";
		try {
			String currentStr = imgStr.substring(imgStr.indexOf(",") + 1);
			System.out.println(currentStr);
			// Base64解码
			byte[] b = decoder.decodeBuffer(currentStr);
			// 生成图片
			File file = new File(fileNameBefore + ".jpg");// 新生成的图片
			OutputStream out = new FileOutputStream(file);
			out.write(b);
			out.flush();
			out.close();
			return file;
		} catch (Exception e) {
			return null;
		}
	}

	public static String fileUpload(MultipartFile file,String filePath) {
		StringTokenizer st = new StringTokenizer(file.getOriginalFilename(), ".");
		String later = null;
		while (st.hasMoreTokens()) {
			later = st.nextToken();
		}
		String fileNameBefore = System.currentTimeMillis() + "";
		String fileName = fileNameBefore + "." + later;
		File targetFile = new File(filePath, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ossClient.putObject(bucketName, fileName, targetFile);
		// ossClient.shutdown();
		targetFile.delete();
		return "https://yunkaihuang.oss-cn-beijing.aliyuncs.com/" + fileName;
	}

	public static String fileUpload(File file) {
		String fileNameBefore = System.currentTimeMillis() + "";
		String fileName = fileNameBefore + ".jpg";
		ossClient.putObject(bucketName, fileName, file);
		// ossClient.shutdown();
		file.delete();
		return "https://yunkaihuang.oss-cn-beijing.aliyuncs.com/" + fileName;
	}

	public static void fileDelete(String fileKey) {
		ossClient.deleteObject(bucketName, fileKey);
	}

}
